package com.bizzard.pet.service.impl;

import com.bizzard.basic.exception.BusinessException;
import com.bizzard.basic.service.IBaiduAiAuditService;
import com.bizzard.basic.util.*;
import com.bizzard.order.domain.OrderPetAcquisition;
import com.bizzard.order.mapper.OrderPetAcquisitionMapper;
import com.bizzard.org.domain.Employee;
import com.bizzard.org.domain.Shop;
import com.bizzard.org.mapper.EmployeeMapper;
import com.bizzard.org.mapper.ShopMapper;
import com.bizzard.pet.domain.Pet;
import com.bizzard.pet.domain.SearchMasterMsg;
import com.bizzard.pet.domain.SearchMasterMsgAuditLog;
import com.bizzard.pet.dto.MsgDto;
import com.bizzard.pet.mapper.PetMapper;
import com.bizzard.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.bizzard.pet.mapper.SearchMasterMsgMapper;
import com.bizzard.pet.query.SearchMasterMsgQuery;
import com.bizzard.pet.service.ISearchMasterMsgService;
import com.bizzard.basic.service.impl.BaseServiceImpl;
import com.bizzard.user.domain.Logininfo;
import com.bizzard.user.domain.User;
import com.bizzard.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private PetMapper petMapper;

    @Override
    public void publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
       // 获取发布寻主消息的用户
        Logininfo logininfo = LoginContext.getLoginUser(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());

        // 1. 添加寻主消息
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);

        // 2. 智能审核
        Boolean textBoo = baiduAiAuditService.textAudit(searchMasterMsg.getTitle() + searchMasterMsg.getName() + searchMasterMsg.getAddress());
        Boolean imageBoo = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());



        if(textBoo && imageBoo){
            //  审核通过： 修改修改寻主消息状态为“1” + 将添加的寻主信息分配给附近的门店  +  发短信通知 + 添加审核日志
            // 设置状态和日志
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核成功");

            // 绑定店铺
            Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
            //50公里以内
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopMapper.loadAll());
            if(nearestShop!=null){
                searchMasterMsg.setShopId(nearestShop.getId());
                //模拟发短信或发邮件
                System.out.println("你有新的订单，请尽快处理："+searchMasterMsg.getTitle());
            }
            searchMasterMsgMapper.update(searchMasterMsg);

            // 添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            //audit_id - 自动审核，没有添加审核人
            log.setState(1);//驳回
            log.setNote("审核成功，请等待工作人员上门");
            searchMasterMsgAuditLogMapper.save(log);

        }else{
            //修改状态和日志
            searchMasterMsg.setState(0);
            searchMasterMsg.setNote("审核失败，内容非法");
            searchMasterMsgMapper.update(searchMasterMsg);

            // 审核失败 ： 修改寻主消息状态为：“0” + 添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            //audit_id - 自动审核，没有添加审核人
            log.setState(0);//驳回
            log.setNote("审核失败，内容非法");
            searchMasterMsgAuditLogMapper.save(log);
            throw new BusinessException("审核失败，内容非法");
        }


    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLoginUser(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLoginUser(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        //如果当前管理员是店铺管理员：要设置shopId
        //如果当前管理员是平台管理员：不设置shopId
        if(employee.getShop_id() !=null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }

        return super.queryPage(query);

    }
    /**
     *   拒单
     */
    @Override
    public void reject(Long msgId) {
        searchMasterMsgMapper.reject(msgId);
    }

    /**
     *  接单
     * @param msgDto
     */
    @Override
    public void accept(MsgDto msgDto) {
        Long empId = msgDto.getHandler();
        Long msgId = msgDto.getMsgId();
        String note = msgDto.getNote();

        //1.校验：当前寻主消息是否已经被接单了
        OrderPetAcquisition orderTem = orderPetAcquisitionMapper.loadByMsgId(msgId);
        if(orderTem != null){
            throw new BusinessException("订单正在处理，请耐心等待!!!");
        }

        //1.创建宠物对象
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = searchMasterMsg2pet(searchMasterMsg);
        petMapper.save(pet);

        //2.创建收购单
        OrderPetAcquisition order = buildOrder(pet,searchMasterMsg,empId);
        orderPetAcquisitionMapper.save(order);

        //3.发短信或邮件告诉收购人在规定时间之内去收购宠物
        System.out.println("你有新的订单，请在规定时间内去收购宠物");

    }

    private OrderPetAcquisition buildOrder(Pet pet, SearchMasterMsg msg, Long empId) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(pet.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(msg.getTitle());
        //两天之后的此刻就是最后收购时间 - 自动通过定时器取消
        long timeTem = System.currentTimeMillis() + 2*24*60*60*1000;
        order.setLastcomfirmtime(new Date(timeTem));
        order.setState(0);//待处理
        order.setPrice(new BigDecimal(msg.getPrice()));
        //paytype//在处理订单时才处理
        order.setPetId(pet.getId());
        order.setUserId(pet.getUserId());
        order.setShopId(pet.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

    private Pet searchMasterMsg2pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice().toString());
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }

}
